<?php

namespace App\Http\Controllers\Web;

use App\Models\Coupon;
use App\Models\UserCoupon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CouponController extends Controller
{
    //用户领取优惠券
    public function getCoupon(Request $request)
    {
        $user_id = Auth::id();
        if (!$user_id) {
            return show(202, '未登录');
        }
        $UserCoupon = UserCoupon::where('user_id',$user_id)
            ->where('coupon_id',$request->id)
            ->where('is_use',0)
            ->first();
        if($UserCoupon){
            return show(203, '该优惠券已领取');
        }
        $Coupon = Coupon::where('id',$request->id)->first();

        if($Coupon->coupon_end_time<date("Y-m-d H:i:s")){
            return show(204, '该优惠券已过期');
        }
        DB::beginTransaction();
        try{
            $data = array(
                'shop_id'=>$request->shop_id,
                'user_id'=>$user_id,
                'coupon_id'=>$request->id,
                'is_use'=>0,
                'created_at'=>date("Y-m-d H:i:s"),
                'updated_at'=>date("Y-m-d H:i:s")
            );
            $resulta = DB::table('user_coupons')->insert($data);

            $resultb = DB::table('coupons')->where('id',$request->id)->increment('receive_num',1,['updated_at'=>date("Y-m-d H:i:s")]);
            if($resulta && $resultb)
            {
                DB::commit();
                return show(200,'优惠券领取成功');
            }
        }catch (\Exception $e){
            DB::rollBack();
            return show(201,'优惠券领取失败');
        }
    }
}
